﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace Controllers
{
    public class EvectionController : BaseController
    {
        //分页查询
        public ActionResult Find(int start, int limit, string idStr,string name)
        {
            int empId;
            IList<int> deptIdList = getAuthedDeptIds("Evection", idStr, out empId);
            EmpBasicInfo ebi = Session["ebi"] as EmpBasicInfo;

            IQueryable<EvectionDTO> q = from r in ctx.ReqEvectionMains
                                          join s in ctx.SignFlows on
                                              new { r.FormNo, IsCurrent = 1 } equals new { s.FormNo, s.IsCurrent }
                                              into t
                                        from x in t.DefaultIfEmpty()
                                        where r.StatusId != 0 || r.EmpId == ebi.Id
                                           orderby r.FormNo descending
                                           select new EvectionDTO
                                          {
                                              FormNo = r.FormNo,
                                              EmpId = r.EmpId,
                                              EmpName = r.Employee.Name,
                                              Cause = r.Cause,
                                              StatusId = r.StatusId,
                                              CheckEmpId = x.CheckEmpId
                                          };
            if (empId != 0)
            {
                q = q.Where(r => r.EmpId == empId);
            }
            else
            {
                q = q.Where(r => (from r1 in ctx.EmpDepPositions where deptIdList.ToArray().Contains(r1.DeptId) select r1.EmpId).Contains(r.EmpId));
            }
            int totalCnt = q.Count();
            if(!string.IsNullOrWhiteSpace(name))
            {
                q = q.Where(r => r.EmpName.Contains(name));
            }
            IList<EvectionDTO> list = q.Skip(start).Take(limit).ToList();
            foreach (var dto in list)
            {
                var listSchedule = from r in ctx.ReqEvectionSchedules where r.FormNo == dto.FormNo select r;
                DateTime dtStart = DateTime.MaxValue;
                DateTime dtEnd = DateTime.MinValue;
                string travel = null;
                foreach (var v in listSchedule)
                {
                    if(dtStart>v.PreStartTime)
                    {
                        dtStart = v.PreStartTime;
                    }
                    if(dtEnd<v.PreEndTime)
                    {
                        dtEnd = v.PreEndTime;
                    }
                    if(string.IsNullOrEmpty(travel))
                    {
                        travel = v.LeavePoint;
                    }
                    travel +="-->"+v.ArrivePoint;
                }
                dto.PreStartTime = dtStart;
                dto.PreEndTime = dtEnd;
                dto.Travel = travel;
            }
            CJson CJson = new CJson();
            string json = CJson.ToJsonString("totalCount:" + totalCnt + ",data", list);
            return Content(json);
        }

        //删除行程明细
        public string DelSchedules(int id)
        {
            string retStr="Succeed";
            ReqEvectionSchedule oriObj = ctx.ReqEvectionSchedules.Single(r => r.Id ==id);
            ctx.ReqEvectionSchedules.DeleteOnSubmit(oriObj);
            try
            {
                ctx.SubmitChanges();
            }
            catch(Exception ex)
            {
                retStr = ex.Message;
            }
            return retStr;
        }

        //删除航程明细
        public string DelVoyages(int id)
        {
            string retStr = "Succeed";
            ReqEvectionVoyage oriObj = ctx.ReqEvectionVoyages.Single(r => r.Id ==id);
            ctx.ReqEvectionVoyages.DeleteOnSubmit(oriObj);
            try
            {
                ctx.SubmitChanges();
            }
            catch (Exception ex)
            {
                retStr = ex.Message;
            }
            return retStr;
        }

        //删除乘机人明细
        public string DelFlighters(int id)
        {
            string retStr = "Succeed";
            ReqEvectionFlighter oriObj = ctx.ReqEvectionFlighters.Single(r => r.Id ==id);
            ctx.ReqEvectionFlighters.DeleteOnSubmit(oriObj);
            try
            {
                ctx.SubmitChanges();
            }
            catch (Exception ex)
            {
                retStr = ex.Message;
            }
            return retStr;
        }

        //删除申请,含明细
        public ActionResult Delete(string formNo)
        {
            var rdto = new ResultMessages();
            rdto.Message = "";
            ReqEvectionMain oriObj = ctx.ReqEvectionMains.Single(r => r.FormNo == formNo);
            ctx.ReqEvectionSchedules.DeleteAllOnSubmit(oriObj.ReqEvectionSchedules);
            ctx.ReqEvectionVoyages.DeleteAllOnSubmit(oriObj.ReqEvectionVoyages);
            ctx.ReqEvectionFlighters.DeleteAllOnSubmit(oriObj.ReqEvectionFlighters);
            ctx.ReqEvectionMains.DeleteOnSubmit(oriObj);
            try
            {
                ctx.SubmitChanges();
                rdto.Message = "删除成功";
                rdto.Result = true;
            }
            catch
            {
                rdto.Message = "删除失败";
                rdto.Result = false;
            }
            return Json(rdto);
        }

        //申请销单()
        public ActionResult Logout(string json)
        {
            var rdto = new ResultMessages();
            rdto.Message = "";
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ReqEvectionMain obj = jss.Deserialize<ReqEvectionMain>(json);
            try
            {
                ReqEvectionMain oriObj = ctx.ReqEvectionMains.Single(r => r.FormNo == obj.FormNo);
                oriObj.RealStartTime = obj.RealStartTime;
                oriObj.RealEndTime = obj.RealEndTime;
                oriObj.RealCost = obj.RealCost;
                oriObj.Remarks = obj.Remarks;
                oriObj.StatusId = obj.StatusId;//4:申请销单,5：销单通过,6：销单退件

                ctx.SubmitChanges();
                rdto.Message = "更新成功";
                rdto.Result = true;
            }
            catch (Exception ex)
            {
                rdto.Message = "更新失败";
                rdto.Result = false;
            }
            return Json(rdto);
        }
    }
}